package com.test.sdk.pay.controller;

import com.test.sdk.common.util.SdkConstants;
import com.test.sdk.pay.wechat.HttpUtil;
import com.test.sdk.pay.wechat.WXPayUtil;
import com.test.sdk.pay.wechat.ZxingUtil;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 徒有琴
 */
@Controller
public class OrderController {
    @RequestMapping("index.html")
    public String index() {
        return "index.html";
    }

    @RequestMapping("order.html")
    public String order(Integer[] gid, Model model) {//商品id
        System.out.println(gid);
        //根据商品id，查询价格 商品的名称等信息
        Map<String, String> param = new HashMap<>();
        param.put("appid", SdkConstants.WECHAT_APP_ID);
        param.put("mch_id", SdkConstants.WECHAT_MCH_ID);
        param.put("nonce_str", System.currentTimeMillis() + "");//替换成自己的方法
        param.put("body", "腾讯会员充值");// 替换成从数据库查的内容
        param.put("out_trade_no", System.currentTimeMillis() + "");//替换成自己的方法
        param.put("total_fee", "1");// 替换成从数据库查的内容
        param.put("spbill_create_ip", "111.203.254.34");//替换成用户真实ip
        param.put("notify_url", SdkConstants.WECHAT_NOTIFY_URL);
        param.put("trade_type", "NATIVE");
        try {
            //把订单insert到数据库  获得一个id

            String xml = WXPayUtil.generateSignedXml(param, "sbNCm1JnevqI36LrEaxFwcaT0hkGxFnC");
            // System.out.println(xml);
            String result = HttpUtil.post(SdkConstants.WECHAT_URL, xml);
            System.out.println(result);
            //

            Map<String, String> order = WXPayUtil.xmlToMap(result);
            String code = order.get("code_url");
            model.addAttribute("name", param.get("body"));
            model.addAttribute("code", code);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "order.html";
    }

    @RequestMapping("code.html")
    public void code(String code, HttpServletResponse response) {
        try {
            BufferedImage image = ZxingUtil.createImage(code, 150, 150);
            ImageIO.write(image, "JPEG", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private final String SUCCESS="<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
    private final String ERROR="<xml><return_code><![CDATA[ERROR]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
    //<xml><appid><![CDATA[wx632c8f211f8122c6]]></appid><bank_type><![CDATA[CFT]]></bank_type><cash_fee><![CDATA[1]]></cash_fee><fee_type><![CDATA[CNY]]></fee_type><is_subscribe><![CDATA[Y]]></is_subscribe><mch_id><![CDATA[1497984412]]></mch_id><nonce_str><![CDATA[1567653930533]]></nonce_str><openid><![CDATA[oUuptwswMZnvt14yansdcAqG3z28]]></openid><out_trade_no><![CDATA[1567653930533]]></out_trade_no><result_code><![CDATA[SUCCESS]]></result_code><return_code><![CDATA[SUCCESS]]></return_code><sign><![CDATA[7F6469ABA594CA749756F49D0E38C468]]></sign><time_end><![CDATA[20190905112544]]></time_end><total_fee>1</total_fee><trade_type><![CDATA[NATIVE]]></trade_type><transaction_id><![CDATA[4200000404201909050270881832]]></transaction_id></xml>
    @RequestMapping("wxpay/callback.html")
    public void callback(HttpServletRequest request,HttpServletResponse response) {
        System.out.println("回调");
        InputStream inputStream = null;
        StringBuilder builder = new StringBuilder();
        BufferedReader reader = null;
        PrintWriter out=null;
        try {
            inputStream = request.getInputStream();
            String s = null;
            out=response.getWriter();
            //按行读取
            reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
            while ((s = reader.readLine()) != null) {
                builder.append(s);
            }
            String xml=builder.toString();
            System.out.println(xml);
            boolean check=WXPayUtil.isSignatureValid(xml,SdkConstants.WECHAT_API_KEY);
            if(check){//成功
                System.out.println("签名成功");
                Map<String,String> data=WXPayUtil.xmlToMap(xml);
                //验证商户号
                //result_code是不是SUCCESS
                //out_trade_no 我们订单表中的订单号 一定要判断订单的状态是否已经是成功的
                //如果是已经成功的订单，直接响应成功，不需要进行操作了，避免重复给用户发货（会员、积分）


                //out_trade_no验证这是一个没有成功的订单
                //首先要验证回调的金额和订单金额是否一致
                //如果一致，更新订单为成功  给用户发货  ；必须保存transaction_id 微信平台D的订单号
                //如果金额不一致 返回失败
                //如果成功，就发消息给队列   看success.html方法
                out .write(SUCCESS);
            }else{//签名错误
                out .write(ERROR);
                System.out.println("失败");
            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
                inputStream.close();
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @Autowired
    private AmqpTemplate amqpTemplate;
    @RequestMapping("success.html")
    public void send(){
        //支付回调的时候有订单号，将订单号当做消息内容发出去
        amqpTemplate.convertAndSend("test1",System.currentTimeMillis()+"s");
    }
}
